const fs = require('fs');

// 重命名
// fs.readdir('./temp_file', function (err, files) {
//     if (err) {
//         return  console.log(err, '目录不存在')
//     }
//     if (files.length) {
//         files.forEach((val, index) => {
//             //  console.log(val, index);

//             fs.readFile('./temp_file/' + val, function (err, files) {
//                 if (err) {
//                     return console.log(err)
//                 }
//                 console.log(files);
//             })
//             let suffix;
//             if (val.split('.')) {
//                 suffix = val.split('.')[val.split('.').length - 1]
//             }
//             // if (file.includes(updateStr)) {  // 含有123 updateStr = 123
//             //     let newName = file.replace(updateStr, newStr) // 替换为456 newStr = 456
//             // }
//             fs.rename(`./temp_file/${files[index]}`, `./temp_file/${index}.${suffix}`, (err) => {
//                 if (!err) {
//                     console.log(index + ' 已修改！')
//                 }
//             })
//         })
//     }
// })

function dataURLtoBlob(dataurl) {
	var arr = dataurl.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {
		type: mime
	});
}



const http = require('http').createServer()

const express = require('express')
var bodyParser = require('body-parser') //加载中间件
//form表单需要的中间件。
var mutipart = require('connect-multiparty');

const app = express();

//设置跨域访问
// app.all('*', function (req, res, next) {
// 	res.header("Access-Control-Allow-Origin", "*");
// 	res.header("Access-Control-Allow-Headers", "*");
// 	res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
// 	res.header("X-Powered-By", ' 3.2.1')
// 	res.header("Content-Type", "application/json;charset=utf-8");
// 	res.header("newArr", "fjalfjlfjlsjlejf")
// 	next();
// });

var mutipartMiddeware = mutipart();
//临时文件的储存位置
app.use(mutipart({
	uploadDir: './temp_file'
}));

//加入这个配置，则在req请求对象上会多出来一个属性：body(可通过req.body来获取表单POST请求体数据了)
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
	extended: false
}))

// parse application/json
app.use(bodyParser.json())

app.use(express.json());

app.get("/", function (req, res) {
	var response = {
		code: 200,
		msg: "1312",
		error: "信息",
		data: req.query
	};
	console.log("/接口", req.query);
	setTimeout(() => {
		res.send(JSON.stringify(response))
	}, 500)
})

app.post("/post", function (req, res) {
	console.log(req.body, "=======post接口消息");
	var response = {
		code: 200,
		msg: "1312",
		error: "post信息",
		data: req.body
	};
	// console.log("/post", req.body);
	res.send(JSON.stringify(response))
})

app.post("/system/login", function (req, res) {
	let {
		username,
		password
	} = req.body;
	let mes = {
		success: "成功",
		error: "失败",
	}
	let flag = ""
	if (username == "123" && password == "456") {
		flag = true;
	} else {
		flag = false;
	}
	var response = {
		code: 200,
		msg: "1312",
		error: "登录信息",
		data: req.body,
		status: flag ? mes.success : mes.error
	};
	console.log("登录", req.body);
	res.send(JSON.stringify(response))
})

app.post("/system/page", mutipartMiddeware, function (req, res) {
	let arr = [];
	let {
		page,
		limt
	} = req.body;
	page = Number(page) - 1;
	limt = Number(limt);

	let readImg = "";

	// fs.readFile('./这是一个路径', 'binary', function (err, originBuffer) {
	//     console.log(originBuffer);
	// })
	readImg = "data:image/jpg;base64," + fs.readFileSync("./img/back.jpeg").toString('base64')
	console.log(req.body, "=======数据信息");
	var response = {
		code: 200,
		msg: "成功",
		error: "分页信息",
		total: 66,
	}
	for (let i = page * limt; i < page * limt + limt; i++) {
		if (i > response.total) {
			break;
		}
		arr.push({
			name: "名字" + i,
			id: "abc" + i,
			status: i % 2 == 0 ? true : false,
			img: readImg
		})
	}
	response.data = arr;
	res.send(JSON.stringify(response))
})

app.post('/file', mutipartMiddeware, (req, res) => {
	console.log("req.files数据：", req.files)
	console.log("post数据：", req.body)

	//返回结果
	var response = {
		code: 200,
		data: {
			name: req.files.file.name,
			file: 'https://emo-file-oss.henghaiwl.cn/avatar/gc7ylpc8qH6319825026352.gif'
		}
	}
	res.end(JSON.stringify(response))
})

app.use(function (req, res) {
	res.setHeader('Content-Type', 'text/plain')
	res.write('404\n')
	res.end(JSON.stringify(req.body, null, 2))
})


var server = app.listen(8008, function () {
	// console.log(server.address());
	var port = server.address().port

	console.log("应用实例，访问地址为 http://localhost:" + port)

})
